package logic

import (
	"context"
	"errors"
	"video-hub/model/cache"
	"video-hub/model/mysql"

	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *videorpc.LoginRequest) (*videorpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var user mysql.User
	if in.LoginTyper == 1 || in.LoginTyper == 2 {
		err := user.FindUserPhone(mysql.DB, in.PhoneNum)
		if err != nil {
			return nil, err
		}
		if user.ID == 0 {
			return nil, errors.New("用户还没有注册")
		}

		if in.LoginTyper == 1 {
			result, _ := cache.Rdb.Get(l.ctx, "send"+in.PhoneNum).Result()
			if in.SendSms != result {
				return nil, errors.New("验证码不正确")
			}
		}

		if in.LoginTyper == 2 {
			if in.Password != user.Password {
				return nil, errors.New("密码不正确")
			}
		}
	}
	if user.AccountStatus == 1 {
		return nil, errors.New("账号已禁用，请联系管理员")
	}
	return &videorpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
